<script setup lang="ts">
/**
 * @author lw
 */
import { ref, watch, computed } from "vue";
import {
  getServiceAllMenuView,
  getActionReportView,
  getServiceWindowView,
} from "../../api/commonApi.ts";

const props = defineProps({
  service: { type: String, required: true },
  active: { type: String, default: "" },
  size: { type: String, default: "small" },
});

const emit = defineEmits<{
  (e: "select", viewMode: "xtree" | "tree" | "kanban" | "report"): void;
}>();

const allViewModes = ref([]);

const available = ref<Record<string, boolean>>({
  xtree: false,
  tree: false,
  kanban: false,
  report: false,
});

const loadAvailable = async () => {
  available.value = { xtree: false, tree: false, kanban: false, report: false };
  if (!props.service) return;
  try {
    const windowView = await getServiceWindowView(props.service);
    if (windowView && windowView.length) {
      const list = windowView[0].viewMode.split(",");
      allViewModes.value = list;
      if (Array.isArray(list)) {
        for (const item of list) {
          const vm = (item || "").toLowerCase();
          if (vm in available.value) {
            available.value[vm] = true;
          }
        }
      }
    }
    const reportList = await getActionReportView(props.service);
    if (Array.isArray(reportList) && reportList.length > 0) {
      available.value.report = true;
    }
  } catch (e) {
    // 静默失败，保持默认 false
  }
};

watch(
  () => props.service,
  () => loadAvailable(),
  { immediate: true }
);

const isActive = (vm: string) => props.active?.toLowerCase() === vm;

const onClick = (vm: "xtree" | "tree" | "kanban" | "report") => {
  if (!available.value[vm]) return;
  emit("select", vm);
};

const viewmodeImages = {
  xtree: "/view/xtree.png",
  tree: "/view/tree.png",
  kanban: "/view/kanban.png",
  report: "/view/report.png",
};
</script>

<template>
  <el-button-group>
    <el-button
      v-for="vm in allViewModes"
      :key="vm"
      :size="size"
      :type="isActive(vm) ? 'primary' : 'default'"
      :plain="!isActive(vm)"
      @click="onClick(vm as any)"
    >
      <el-image
        :src="viewmodeImages[vm]"
        alt="viewmode"
        class="w-[16px] h-[16px]"
      />
    </el-button>
  </el-button-group>
</template>

<style scoped></style>
